package com.af.community.smart.business

import android.os.Bundle
import android.view.MotionEvent
import com.af.community.smart.base.BaseActivity
import com.af.community.smart.base.invisible
import com.af.community.smart.base.oneClick
import com.af.community.smart.base.visible
import com.af.community.smart.model.FormData
import com.af.community.smart.model.HouseData
import com.af.community.smart.share.Const
import com.af.community.smart.utils.*
import com.af.community.smart.view.FullyLinearLayoutManager
import com.af.community.smart.viewmodel.HouseViewModel
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.lzg.extend.jackson.JsonUtil
import kotlinx.android.synthetic.main.activity_house_detail.*
import kotlinx.android.synthetic.main.include_layout_map2.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel

class HouseDetailActivity : BaseActivity() {

    private val list = ArrayList<FormData>()
    private var mData: HouseData? = null
    private var houseId = ""
    private var houseType = ""
    private var houseTypeName = ""
    private var isPatrol = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_house_detail)
        initTitle(name = "编辑")
        initMapView()

        observe("house_edit") {
            mData = JsonUtil.getMapperInstance().readValue(it, HouseData::class.java)
            setData(it)
            setLocation(mData?.lat.orEmpty(), mData?.lng.orEmpty())
        }

        getViewModel().getHouseDetail(houseId)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByNoError(
                event = getViewModel(),
                onSuccess = {
                    mData = JsonUtil.getMapperInstance().readValue(it, HouseData::class.java)
                    setData(it)
                    setLocation(mData?.lat.orEmpty(), mData?.lng.orEmpty())
                }
            )
    }

    override fun getViewModel() = getViewModel<HouseViewModel>()

    override fun initTitle(title: String, name: String) {
        houseId = intent.getStringExtra("houseId").orEmpty()
        houseType = intent.getStringExtra("houseType").orEmpty()
        houseTypeName = intent.getStringExtra("houseName").orEmpty()
        isPatrol = intent.getBooleanExtra("isPatrol", false)
        super.initTitle(if (houseTypeName.isEmpty()) "详情" else houseTypeName, name)

        if (isPatrol) bt_add.visible()

        when (houseType) {
            "ht_zf" -> list.addAll(Const.listOne)
            "ht_czf" -> list.addAll(Const.listTwo)
            "ht_zjcs" -> list.addAll(Const.listThree)
            "ht_yldw" -> list.addAll(Const.listFour)
            "ht_xzdw" -> list.addAll(Const.listFive)
            "ht_xhhzz" -> list.addAll(Const.listSix)
            "ht_xjjzz" -> list.addAll(Const.listSeven)
            "ht_zacs" -> list.addAll(Const.listEight)
            "ht_aqsc" -> list.addAll(Const.listNine)
            "ht_xfaq" -> list.addAll(Const.listTen)
            "ht_xx" -> list.addAll(Const.listEleven)
            "ht_qy" -> list.addAll(Const.listTwelve)
            "ht_yhdw" -> list.addAll(Const.listThirteen)
            "ht_jrxt" -> list.addAll(Const.listFourteen)
            "ht_qtcs" -> list.addAll(Const.listFifteen)
        }

        house_list.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(baseContext)
        }

        mAdapter = SlimAdapter.create()
            .register<FormData>(R.layout.item_house_list2) { data, injector ->
                injector.text(R.id.item_house_left, "${data.title}：")
                    .text(R.id.item_house_right, data.content)
            }
            .attachTo(house_list)

        tvRight?.oneClick {
            if (mData != null) {
                startActivity<HouseAddActivity>(
                    "label" to houseTypeName,
                    "value" to houseType,
                    "data" to mData
                )
            }
        }

        bt_add.oneClick {
            if (mData != null) {
                startActivity<PatrolAddActivity>("house" to mData)
            }
        }
    }

    private fun initMapView() {
        house_map.apply {
            //隐藏百度Logo
            getChildAt(1).invisible()
            //隐藏缩放控件
            showZoomControls(false)
            //隐藏比例尺
            showScaleControl(false)
            map.apply {
                //普通地图
                mapType = BaiduMap.MAP_TYPE_NORMAL
                //开启定位图层
                isMyLocationEnabled = true
                //隐藏指南针
                uiSettings.isCompassEnabled = false
                //是否启用地图俯视功能
                uiSettings.isOverlookingGesturesEnabled = false

                setMyLocationConfiguration(
                    MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL,
                        false,
                        null
                    )
                )

                setOnMapTouchListener {
                    house_scroll.requestDisallowInterceptTouchEvent(it.action != MotionEvent.ACTION_UP)
                }
            }
        }

    }

    private fun setLocation(lat: String, lng: String) {
        val latitude = lat.toNotDouble()
        val longitude = lng.toNotDouble()

        house_map.map.apply {
            isMyLocationEnabled = true
            setMyLocationData(
                MyLocationData.Builder()
                    .accuracy(0f)         //精度圈半径
                    .latitude(latitude)   //纬度
                    .longitude(longitude) //经度
                    .build()
            )

            animateMapStatus(
                MapStatusUpdateFactory.newMapStatus(
                    MapStatus.Builder()
                        .target(LatLng(latitude, longitude))
                        .zoom(18f)
                        .build()
                )
            )
        }
    }


    private fun setData(json: String) {
        val obj = JSONObject(json)
        list.forEach {
            val value = obj.optNotNull(it.contentKey)
            it.content = when (it.contentKey) {
                "foundDate" -> value.toFormatString(eFormat = "yyyy-MM-dd")
                "buildingArea" -> if (value.isEmpty()) "" else "${value}㎡"
                "registerAmounts" -> if (value.isEmpty()) "" else "${value.formatAmount()}元"
                "right", "prod", "security",
                "establish", "volunteer" -> if (value == "1") "是" else "否"
                else -> value
            }
        }
        mAdapter.updateData(list)
    }

    override fun onResume() {
        super.onResume()
        house_map.onResume()
    }

    override fun onPause() {
        super.onPause()
        house_map.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        house_map.map.isMyLocationEnabled = false
        house_map.onDestroy()
    }

}
